using Gtk;
using Npgsql;
using PTransaction;
using System;
using System.Data;

namespace PTransaction
{
	public partial class TransactionView : Gtk.Window
	{
		private NpgsqlTransaction transaction;
		private NpgsqlConnection connection= DbConnection.Instance.Connection;
		
		public TransactionView () : base(Gtk.WindowType.Toplevel)
		{
			this.Build ();
		
//			prueba();
			
			goForwardAction.Activated += delegate {
				transaction= connection.BeginTransaction();
				labelStatus.LabelProp= "BeginTransaction";
			};
			
			executeAction.Activated += delegate {
				string sql= textView.Buffer.Text;
				NpgsqlCommand commanad= connection.CreateCommand();
				commanad.CommandText= sql;
//				commanad.CommandTimeout= 
				try {
					commanad.ExecuteNonQuery();
				labelStatus.LabelProp= "Command OK";
				}
				catch(Exception e) {
					MessageDialog messageDialog= new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, e.Message);
					messageDialog.Run();
					messageDialog.Destroy();
				}
			};
			
			applyAction.Activated += delegate {
				transaction.Commit();
				labelStatus.LabelProp= "Transaction Commit";
			};
			
			
			cancelAction.Activated += delegate {
				transaction.Rollback();
				labelStatus.LabelProp= "Tansaction Rollback";
			};
		}
		
	
		private void prueba() {
			try {
				NpgsqlCommand command1= DbConnection.Instance.Connection.CreateCommand();
				command1.CommandText= "UPDATE articulo SET precio=precio+0.1 WHERE id=30";
				command1.ExecuteNonQuery();
				
				NpgsqlCommand command2= DbConnection.Instance.Connection.CreateCommand();
				command2.CommandText= "UPDATE articulo SET precio=precio-0.1 WHERE id=2";
				if(command2.ExecuteNonQuery() != 1)
					throw new Exception("No existe artículo con el id=2");
				
				transaction.Commit();
			}
			catch(Exception e) {
				transaction.Rollback();
				MessageDialog messageDialog= new MessageDialog(null, DialogFlags.Modal, MessageType.Error, ButtonsType.Ok, e.Message);
				messageDialog.Run();
				messageDialog.Destroy();
			}
		}
	}
}
